const formatTime = (date) => {
  var date = new Date(date);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return `${[year, month, day].map(formatNumber).join("/")} ${[
    hour,
    minute,
    second,
  ]
    .map(formatNumber)
    .join(":")}`;
};

const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : `0${n}`;
};

const throttle = (fn, gapTime) => {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500;
  }
  let _lastTime = null;
  let _nowTime = +new Date();
  if (_nowTime - _lastTime > gapTime || !_lastTime) {
    fn.apply(this, arguments);
    _lastTime = _nowTime;
  }
};
const throttle2 = (fn, wait = 1500) => {
  var flag = true;
  var timer = null;
  return function () {
    if (flag) {
      fn.apply(this, arguments);
      flag = false;
      timer = setTimeout(() => {
        flag = true;
      }, wait);
    }
  };
};

function debounce(func, wait, immediate) {
  let timer;

  return function () {
    let context = this;
    let args = arguments;

    if (timer) clearTimeout(timer);
    if (immediate) {
      var callNow = !timer;
      timer = setTimeout(() => {
        timer = null;
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      timer = setTimeout(() => {
        func.apply(context, args)
      }, wait);
    }
  }
}

const withTokenFn = (fb) => {
  if (!wx.getStorageSync("token") || !wx.getStorageSync("bindMobile")) {
    throttle(() => {
      wx.navigateTo({
        url: `../login/login`,
      });
    }, 2000);
    return;
  }
  fb();
};

module.exports = {
  formatTime,
  throttle,
  throttle2,
  withTokenFn,
  debounce
};